package http

import (
	"github.com/bighuangbee/gokit/network/api"
	"github.com/bighuangbee/gokit/storage/gorm"
	"github.com/gin-gonic/gin"
	"strconv"
)

func BindParams(c *gin.Context, obj interface{})error{
	if err := c.ShouldBind(obj); err != nil {
		api.InvalidParams(c, err)
		return err
	}
	return nil
}

func ShouldBind(c *gin.Context, obj interface{}){
	if err := c.ShouldBind(obj); err != nil {
		api.InvalidParams(c, err)
	}
}

func BindJSON(c *gin.Context, obj interface{}) error{
	if err := c.ShouldBindJSON(obj); err != nil {
		api.InvalidParams(c, err)
		return err
	}
	return nil
}

const (
	PageDefault = 1
	LengthDefault = 10
)

func GetPageQuery(c *gin.Context)(*gorm.PageQuery){
	var p gorm.PageQuery
	if err := c.ShouldBind(&p); err != nil {
		return &gorm.PageQuery{}
	}
	if p.Page == 0{
		p.Page = PageDefault
	}
	if p.Length == 0{
		p.Length = LengthDefault
	}

	return &p
}

func GetQueryUint(c *gin.Context, key string)(uint){
	p, _ :=  strconv.ParseUint(c.Query(key), 10, 64)
	return uint(p)
}

func GetUserId(c *gin.Context)(int64){
	return c.GetInt64("user_id")
}

func GetCompanyId(c *gin.Context)(uint){
	return uint(c.GetInt64("company_id"))
}

func GetUserInfo(c *gin.Context)(*UserInfo){
	return &UserInfo{
		CompanyId: uint(c.GetInt64("company_id")),
		UserId:    c.GetInt64("user_id"),
		UserName:  c.GetString("username"),
		Nickname:  c.GetString("nickname"),
	}
}


type Action int8

const (
	ActionDisable = Action(0)
	ActionEnable = Action(1)
	ActionDelete = Action(2)
)
type BatchAction struct {
	Ids	   []uint `json:"ids" form:"ids"`
	Id     []interface{} `json:"id" form:"id" binding:"required"`
	Action Action  `json:"action" form:"action"`
}

type UserInfo struct {
	CompanyId uint  `json:"company_id"`
	UserId int64 `json:"user_id"`
	UserName string  `json:"username"`
	Nickname string  `json:"nickname"`
}
